package com.template.app.editor;

import java.beans.PropertyEditorSupport;

import org.springframework.util.StringUtils;

import com.template.app.exception.ObjectNotFoundException;
import com.template.app.model.Identifiable;
import com.template.app.service.GenericService;

public class IdEditorSupport extends PropertyEditorSupport {

	private Class<?> clazz;
	private GenericService service;
	
	public IdEditorSupport(Class<?> clazz, GenericService service) {
		this.clazz = clazz;
		this.service = service;
	}
	
	protected Object getObject(String stringId) {
		stringId = StringUtils.trimAllWhitespace(stringId);
		if (stringId == null || stringId.isEmpty()) {
			return null;
		}
		
		Integer id = null;
		try {
			id = Integer.valueOf(stringId);
		} catch (NumberFormatException e) {
			return null;
		}
		
		Object obj = null;
		if (service.exists(clazz, id)) {
			obj = service.get(clazz, id);
		} else {
			throw new ObjectNotFoundException(clazz, id);
		}
		
		return obj;
	}
	
	protected String getString() {
		Object obj = getValue();
		if (obj instanceof Identifiable) {
			return ((Identifiable) obj).getId().toString();
		}
		return super.getAsText();
	}
	
}
